import config from '../config.js'
console.log(config);
let tui = {};
tui.delayed = null;
tui.tokenKey = config.tokenKey;
tui.defToken = config.defToken;
tui.loadding = false;
tui.webUrl = config.host;
tui.interfaceUrl = config.host + '/api';
tui.requestPageLength = config.pageLength;
/**
 * 内置提示
 */
tui.toast = function(text, icon, callback, duration) {
	uni.showToast({
		title: text || "出错啦~",
		icon: icon ? icon : "none",
		duration: duration || 1500,
		success(res) {
			setTimeout(function() {
				callback && callback(res);
			}, duration);
		},
	});
};
/**
 * 提示
 */
tui.alert = function(title, content, callback, confirmColor, confirmText) {
	uni.showModal({
		title: title || '提示',
		content: content,
		showCancel: false,
		cancelColor: "#555",
		confirmColor: confirmColor || "#5677fc",
		confirmText: confirmText || "确定",
		success(res) {
			callback && callback(res);
		}
	})
};
/**
 * 提示
 */
tui.confirm = function(title, content, callback, confirmColor, confirmText) {
	uni.showModal({
		title: title || '提示',
		content: content,
		showCancel: true,
		cancelColor: "#555",
		confirmColor: confirmColor || "#5677fc",
		confirmText: confirmText || "确定",
		success(res) {
			callback && callback(res);
		}
	})
};
tui.success = function() {};
tui.error = function() {};
tui.htmlInit = function(html) {
	html = html.replace(/\<p[\sa-zA-Z0-9\="\:\;\-]*>\<br><img/gi, '<p style="font-size:0;text-indent:0;"><img');
	html = html.replace(/\<p[\sa-zA-Z0-9\="\:\;\-]*>\<img/gi, '<p style="font-size:0;text-indent:0;"><img');
	return html;
};

/**
 * showLoading
 */
tui.showLoading = function(title, time = 0, mask = true) {
	uni.showLoading({
		mask: mask,
		title: title || '请稍候...'
	});
	if (time > 0) {
		setTimeout(function() {
			uni.hideLoading();
		}, time * 1000);
	}
};
tui.xhrReturn = function(data, callback, duration) {
	if (data.info.length < 9) {
		switch (data.status) {
			case 0:
				tui.successMsg(data.info, function(res) {
					callback && callback(res);
				}, duration);
				break;
			default:
				tui.errorMsg(data.info, function(res) {
					callback && callback(res);
				}, duration);
				break;
		}
	} else {
		tui.toast(data.info, 'none', function(res) {
			callback && callback(res);
		}, duration);
	}
};
/**
 * success
 */
tui.successMsg = function(text, callback, duration) {
	uni.showToast({
		title: text || "successMsg~",
		image: "../static/components/icon_success.png",
		duration: duration || 1500,
		success(res) {
			setTimeout(function() {
				callback && callback(res);
			}, duration);
		},
	});
};
/**
 * error
 */
tui.errorMsg = function(text, callback, duration) {
	uni.showToast({
		title: text || "errorMsg~",
		image: "../static/components/icon_error.png",
		duration: duration || 1500,
		success(res) {
			setTimeout(function() {
				callback && callback(res);
			}, duration);
		},
	});
};
/**
 * 将json对象转换为url格式
 */
tui.initParamsData = function(json) {
	let getParams = Object.keys(json).map(function(key) {
		return key + "=" + json[key];
	}).join("&");
	return getParams;
};
/**
 * param转换为数组
 */
tui.unParamsData = function(param) {
	let arr = param.split('&'); //获取浏览器地址栏中的参数
	let res = {}
	for (let i = 0; i < arr.length; i++) { //遍历参数
		if (arr[i].indexOf('=') != -1) { //如果参数中有值
			let str = arr[i].split('=');
			res[str[0]] = str[1];
		} else { //如果参数中无值
			res[arr[i]] = '';
		}
	}
	return res
};
tui.getUrlkey = function(url) {
	var params = {};
	var arr = url.split("&");
	for (var i = 0, l = arr.length; i < l; i++) {
		var a = arr[i].split("=");
		params[a[0]] = a[1];
	}
	return params;
};
/**
 * request请求发起
 */
tui.request = function(url = "", method = "GET", urlParams = {}, postData = {}, token = true, loading = false, isDelay = false) {
	if (loading) {
		if (isDelay) {
			tui.delayed = setTimeout(() => {
				tui.loadding = true;
				tui.showLoading();
			}, 1000)
		} else {
			tui.loadding = true;
			tui.showLoading();
		}
	}
	urlParams.apiVersion = config.apiVersion;
	if (config.environment.check) {
		// #ifdef MP-WEIXIN
		urlParams.appId = config.wxAppId;
		urlParams.environment = 'wx_applets';
		// #endif
		// #ifdef APP-PLUS
		urlParams.environment = 'app-plus';
		// #endif
		// #ifdef H5
		urlParams.environment = 'h5';
		// #endif
		// #ifndef APP-PLUS||MP-WEIXIN||H5
		urlParams.environment = 'other';
		// #endif
	} else {
		urlParams.environment = config.environment.default;
	}
	url = tui.interfaceUrl + url + ".json?" + tui.initParamsData(urlParams);
	let header = {
		'content-type': 'application/json', // isForm ? 'application/x-www-form-urlencoded' : 'application/json',
	};
	header.Authorization = token ? tui.getToken() : 0;
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: postData,
			header: header,
			method: method,
			dataType: 'json',
			success: (res) => {
				if (loading) {
					if (isDelay) {
						clearTimeout(tui.delayed)
						tui.delayed = null;
					} else {
						uni.hideLoading();
					}
				}
				resolve(res.data)
			},
			fail: (res) => {
				clearTimeout(tui.delayed)
				tui.delayed = null;
				console.error(url, postData, header, method);
				tui.errorMsg("网络不给力，请稍后再试~")
				reject(res)
			}
		})
	})
};
/**
 * GET请求
 */
tui.get = async function(url, params = {}, token = true, loading = false, isDelay = false) {
	return tui.request(url, 'GET', params, {}, token, loading, isDelay)
};
/**
 * POST请求
 */
tui.post = async function(url, data = {}, params = {}, token = true, loading = false, isDelay = false) {
	return tui.request(url, 'POST', params, data, token, loading, isDelay)
};
/**
 * PUT请求
 */
tui.put = async function(url, data = {}, params = {}, token = true, loading = false, isDelay = false) {
	return tui.request(url, 'PUT', params, data, token, loading, isDelay)
};
/**
 * DEL请求
 */
tui.del = async function(url, data = {}, params = {}, token = true, loading = false, isDelay = false) {
	return tui.request(url, 'DELETE', params, data, token, loading, isDelay)
};
/**
 * 上传文件
 */
tui.uploadFile = function(filePath, fileName, formData = {}, loading = true, url = '/upload/form.json') {
	if (loading) {
		tui.showLoading()
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: tui.interfaceUrl + url,
			filePath: filePath,
			name: fileName,
			header: {
				'Authorization': tui.getToken()
			},
			formData: formData,
			success(res) {
				if (loading) {
					uni.hideLoading()
				}
				res.data = JSON.parse(res.data);
				resolve(res.data);
			},
			fail(res) {
				reject(res)
			}
		})
	})
};
/**
 * 设置缓存
 */
tui.setCache = function(dataKey, val, call) {
	try {
		uni.setStorageSync(dataKey, val);
		call && call(dataKey, val);
	} catch (e) {
		console.log('setCache=>', e);
	}
};
/**
 * 获取缓存
 */
tui.getCache = function(dataKey) {
	let data = false;
	try {
		data = uni.getStorageSync(dataKey);
		switch (typeof(data)) {
			case 'object':
				return data;
			case 'number':
				return data;
			case 'string':
				return data.length > 0 ? data : false;
			case 'boolean':
				return data;
			default:
				console.log('getCache=>', typeof(data));
		}
	} catch (e) {
		console.log('getCache=>', e);
	}
};
/**
 * 删除缓存
 */
tui.delCache = function(dataKey, call) {
	try {
		uni.removeStorageSync(dataKey);
		call && call();
	} catch (e) {
		console.log('delCache=>', e);
	}
};
/**
 * 清除所有缓存
 */
tui.clearCache = function(call) {
	try {
		uni.clearStorageSync();
		call && call();
	} catch (e) {
		console.log('clearCache=>', e);
	}
};
/**
 * 判断是否登录
 */
tui.isLogin = function() {
	return tui.getCache(tui.tokenKey) ? true : false;
};
/**
 * 调试环境判断
 */
tui.isDebug = function() {
	if (tui.getCache('appInit').isDebug === true) {
		return true;
	} else {
		if (tui.isLogin()) {
			if (tui.inArray(tui.getCache('user').token.uid, tui.getCache('appInit').debugMemberArr)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
};
tui.getColorSite = function() {
	return tui.getCache('appInit').colorSite;
};
/**
 * 判断是否为安卓
 */
tui.isAndroid = function() {
	let res = uni.getSystemInfoSync();
	return res.platform.toLocaleLowerCase() === "android"
};
/**
 * 判断是否为苹果X
 */
tui.isPhoneX = function() {
	let res = uni.getSystemInfoSync();
	let iphonex = false;
	let models = ['iphonex', 'iphonexr', 'iphonexsmax', ];
	for (let i = 11; i <= 14; i++) {
		models.push('iphone' + i);
		models.push('iphone' + i + 'pro');
		models.push('iphone' + i + 'promax');
	}
	let model = res.model.replace(/\s/g, "").toLowerCase();
	console.log(models, model);
	if (models.includes(model)) {
		iphonex = true;
	}
	return iphonex;
};
/**
 * 获取token
 */
tui.getToken = function() {
	return tui.getCache(tui.tokenKey) ? tui.getCache(tui.tokenKey) : 0;
};
/**
 * 字符串转json
 */
tui.str2json = function(str) {
	return eval('(' + str + ')');
};
/**
 * 字符串转数组
 */
tui.str2arr = function(str, ext = ",") {
	return str.split(ext);
};
/**
 * 数组转字符串
 */
tui.arr2str = function(arr, ext = ',') {
	return arr.join(ext);
};
/**
 * json转数组
 */
tui.obj2arr = function(object) {
	let arr = [];
	for (let i in object) {
		arr.push(object[i].name);
	}
	return arr;
};
/**
 * 字符串补 0
 */
tui.strAppend = function(num, n) {
	let len = num.toString().length;
	while (len < n) {
		num = "0" + num;
		len++;
	}
	return num;
};
/**
 * 判断是否包含于数组
 */
tui.inArray = function(search, array) {
	for (let i in array) {
		if (array[i] == search) {
			return true;
		}
	}
	return false;
};
/**
 * 对象搜索
 */
tui.objSearch = function(obj, key, val) {
	let call = false;
	for (let i = 0; i < obj.length; i++) {
		if (obj[i][key] == val) {
			call = true;
			break;
		}
	}
	return call;
};
/**
 * 去空格
 */
tui.trim = function(value) {
	return value.replace(/(^\s*)|(\s*$)/g, "");
};
/**
 * 内容替换
 */
tui.replaceAll = function(text, repstr, newstr) {
	return text.replace(new RegExp(repstr, "gm"), newstr);
};
/**
 * 格式化手机号码
 */
tui.formatNumber = function(num) {
	return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
};
/**
 * 金额格式化
 */
tui.rmoney = function(money) {
	return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(/\,$/, '').split('').reverse().join('');
};
/**
 * 日期格式化
 */
tui.formatDate = function(time = false, format = false) {
	let timeString = time ? time : new Date().getTime();
	let now = new Date(timeString);
	let year = now.getFullYear();
	let month = now.getMonth() + 1;
	let date = now.getDate();
	let hour = now.getHours();
	let minute = now.getMinutes();
	let second = now.getSeconds();
	let formatStr = '';
	format = format || 'Y-m-d H:i:s';
	formatStr = format;
	formatStr = formatStr.replace("Y", year);
	formatStr = formatStr.replace("m", tui.strAppend(month, 2));
	formatStr = formatStr.replace("d", tui.strAppend(date, 2));
	formatStr = formatStr.replace("H", tui.strAppend(hour, 2));
	formatStr = formatStr.replace("i", tui.strAppend(minute, 2));
	formatStr = formatStr.replace("s", tui.strAppend(second, 2));
	return {
		year: year,
		month: month,
		date: date,
		hour: hour,
		minute: minute,
		second: second,
		now: now,
		timestamp: parseInt(now.getTime() / 1000),
		format: formatStr,
	};
};
tui.initTimeData = function(time) {
	let timeString = time ? time : new Date().getTime();
	let now = new Date(timeString);
	let year = now.getFullYear();
	let month = now.getMonth() + 1;
	month = (month > 9) ? month : '0' + month;
	let date = now.getDate();
	let hour = now.getHours();
	let minute = now.getMinutes();
	let second = now.getSeconds();
	return {
		year,
		month,
		date,
		hour,
		minute,
		second,
		now
	};
};
/**
 * 保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面
 */
tui.urlHref = function(url, isVerify = false) {
	if (isVerify && !tui.isLogin()) {
		uni.navigateTo({
			url: config.loginPath,
		})
	} else {
		uni.navigateTo({
			url: url,
			animationType: 'zoom-fade-out',
		});
	}
};
/**
 * 保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面
 */
tui.urlOpen = function(url, isVerify = false) {
	if (isVerify && !tui.isLogin()) {
		uni.redirectTo({
			url: config.loginPath,
		})
	} else {
		uni.redirectTo({
			url: url,
			animationType: 'slide-in-top',
		});
	}
};
/**
 * 保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面
 */
tui.urlBlank = function(url) {
	uni.reLaunch({
		url: url,
		animationType: 'none',
	});
};
/**
 * 关闭当前页面，返回上一页面或多级页面
 */
tui.urlBack = function(len = 1) {
	uni.navigateBack({
		delta: len,
		animationType: 'none',
	});
};
/**
 * 保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面
 */
tui.urlTab = function(url) {
	uni.switchTab({
		url: url,
	});
};
/**
 * 一键拨号
 */
tui.callPhone = function(tel) {
	uni.makePhoneCall({
		phoneNumber: tel, // 手机号
		success: (res) => {
			console.log('callPhone->调用成功!', tel)
		},
		fail: (res) => {
			console.log('callPhone->调用失败!', tel)
		},
	})
};
/**
 * 设置用户信息缓存
 */
tui.removeUserInfo = function(call) {
	tui.delCache('token', function() {
		tui.delCache('user', function() {
			tui.delCache('lastUppAddressData', function() {
				tui.delCache('lastUppUserInvoiceTitleData', function() {
					tui.delCache('parent_id', function() {
						call && call();
					});
				});
			});
		});
	});
};
tui.setUserInfo = function(data, call) {
	console.log('setUserInfo->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', data);
	tui.setCache("user", data, function() {
		tui.setCache(tui.tokenKey, data.token.token, function() {
			if (typeof data.userAddress !== 'undefined' && typeof data.userAddress.id !== 'undefined') {
				let lastUppAddressData = tui.getCache('lastUppAddressData');
				if (lastUppAddressData !== false) {
					console.log("typeof lastUppAddressData.id !== 'undefined'", typeof lastUppAddressData.id !== 'undefined');
					console.log("typeof lastUppAddressData.member_id !== 'undefined'", typeof lastUppAddressData.member_id !== 'undefined');
					console.log("typeof lastUppAddressData.member_id === data.userInfo.id", lastUppAddressData.member_id === data.userInfo.id);
					if (
						typeof lastUppAddressData.id !== 'undefined' &&
						typeof lastUppAddressData.member_id !== 'undefined' &&
						lastUppAddressData.member_id === data.userInfo.id &&
						true
					) {

					}
				} else {
					tui.setCache('lastUppAddressData', data.userAddress);
				}
			}
			if (tui.getCache("parent_id")) {
				let parent_id = parseInt(tui.getCache("parent_id"));
				if (data.userInfo.id != parent_id) {
					tui.put('/user/bind', {
						parent_id: parent_id
					}).then(function(bind) {
						console.log('绑定会员关系->' + parent_id);
						tui.delCache('parent_id', function() {
							call && call(data);
						});
					});
				} else {
					tui.delCache('parent_id', function() {
						console.log('无法与自己绑定->' + parent_id);
						call && call(data);
					});
				}
			} else {
				call && call(data);
			}
		});
	});
};
/**
 * 刷新用户信息缓存
 */
tui.upDataUserInfo = function(call) {
	tui.get('/user/init').then(function(res) {
		switch (res.status) {
			case 0:
				tui.setUserInfo(res.data, function(response) {
					call && call(res);
				});
				break;
			case -99:
				console.log('upDataUserInfo=>', res);
				tui.delCache("token", function() {
					call && call(res);
				});
				break;
			default:
				call && call(res);
				break;
		}
	});
};
tui.initCache = function(call) {
	let version = tui.getCache("version") ? tui.getCache("version") : 0;
	let param = {};
	tui.get('/version', param, false, false, true).then(function(response) {
		if (response.status === 0) {
			console.log('本地版本:' + version + ' =>>>>>>>>>>>>API版本:' + response.data.version)
			if (version !== response.data.version) {
				console.log('更新缓存版本:' + response.data.version)
				tui.delCache("user", function() {
					tui.delCache("version", function() {
						tui.delCache("appInit", function() {
							tui.setCache('version', response.data.version, function() {
								tui.get('/init', param, false, false, true).then(function(response) {
									if (response.status === 0) {
										tui.setCache('appInit', response.data, function(dataKey, response) {
											call && call(response);
										});
									} else {
										tui.initCache(call);
									}
								});
							});
						});
					});
				});
			} else {
				call && call(tui.getCache('appInit'));
			}
		} else {
			tui.initCache(call);
		}
	});
};
/**
 * 支付宝支付
 */
tui.aLiPay = function(payConfig, successFun, errorFun) {
	// #ifdef APP-PLUS
	uni.requestPayment({
		provider: "alipay",
		orderInfo: payConfig.data, //微信、支付宝订单数据
		success(res) {
			console.log('success:' + JSON.stringify(res));
			successFun && successFun(res);
		},
		fail(err) {
			console.log('fail:' + JSON.stringify(err));
			errorFun && errorFun(err)
		},
	});
	// #endif
	// #ifndef APP-PLUS
	tui.toast('支付环境未定义+alipay', 'none');
	// #endif
};
/**
 * 微信支付
 */
tui.wxPay = function(payConfig, successFun, errorFun) {
	// #ifdef APP-PLUS
	uni.requestPayment({
		provider: "wxpay",
		signType: "MD5",
		orderInfo: JSON.stringify({
			"appid": payConfig.appid, //对应的appid
			"noncestr": payConfig.noncestr,
			"package": payConfig.package,
			"partnerid": payConfig.partnerid,
			"prepayid": payConfig.prepayid,
			"timestamp": payConfig.timestamp,
			"sign": payConfig.sign //二次签名
		}),
		success(res) {
			console.log('success:' + JSON.stringify(res));
			successFun && successFun(res);
		},
		fail(err) {
			console.log('fail:' + JSON.stringify(err));
			errorFun && errorFun(err);
		},
	})
	// #endif
	// #ifdef MP-WEIXIN
	uni.requestPayment({
		provider: "wxpay",
		timeStamp: payConfig.timeStamp,
		nonceStr: payConfig.nonceStr,
		package: payConfig.package,
		signType: payConfig.signType,
		paySign: payConfig.paySign,
		success(res) {
			console.log('success:' + JSON.stringify(res));
			successFun && successFun(res);
		},
		fail(err) {
			console.log('fail:' + JSON.stringify(err));
			errorFun && errorFun(err);
		},
	})
	// #endif
	// #ifndef APP-PLUS||MP-WEIXIN
	tui.toast('支付环境未定义+wxpay', 'none');
	// #endif
};
tui.rgbToHex = function(r, g, b) {
	return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
};
// rpx转px
tui.rpxToPx = function(rpx) {
	const screenWidth = uni.getSystemInfoSync().screenWidth
	return (screenWidth * Number.parseInt(rpx)) / 750
};

// px转rpx
tui.pxToRpx = function(px) {
	const screenWidth = uni.getSystemInfoSync().screenWidth
	return (750 * Number.parseInt(px)) / screenWidth
};
tui.toHex = function(n) {
	n = parseInt(n, 10);
	if (isNaN(n)) return "00";
	n = Math.max(0, Math.min(n, 255));
	return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16);
};
tui.hexToRgb = function(hex) {
	let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
	return result ? {
		r: parseInt(result[1], 16),
		g: parseInt(result[2], 16),
		b: parseInt(result[3], 16)
	} : null;
};
/**
 * 公共第三方登录
 */
tui.publicLogin = function(type, call) {
	switch (type) {
		case 'weixin':
			uni.login({
				provider: 'weixin',
				success(res) {
					tui.post('/user/login', {
						access_token: res.authResult.access_token,
						openid: res.authResult.openid
					}, {
						type: 'wx_app'
					}, false).then(function(res) {
						switch (res.status) {
							case 0:
								tui.setUserInfo(res.data, function(response) {
									call && call(response);
								});
								break;
							default:
								console.log('publicLogin=>', res);
								break;
						}
					});
				}
			});
			break;
		default:
			console.log('publicLogin=>', type)
			break;
	}
}
// #ifdef MP-WEIXIN
tui.wxLogin = function(call, log = false) {
	if (tui.isLogin() === false) {
		tui.wxAppletsLogin(function(response) {
			log && console.log('wxLogin->++++++++++++++++++++++++++++++++++++++++++++未登录直接登录', response);
			call && call(response);
		});
	} else {
		uni.checkSession({
			success(success) {
				tui.upDataUserInfo(function(response) {
					switch (response.status) {
						case 0:
							log && console.log('wxLogin->++++++++++++++++++++++++++++++++++++++++++++刷新登录状态', response.data);
							call && call(response.data);
							break;
						default:
							log && console.log('wxLogin->++++++++++++++++++++++++++++++++++++++++++++状态错误重新登录', response.data);
							tui.wxAppletsLogin(function(response) {
								log && console.log('wxLogin->++++++++++++++++++++++++++++++++++++++++++++重新登录成功', response);
								call && call(response);
							});
							break;
					}
				});
			},
			fail(err) {
				tui.wxAppletsLogin(function(response) {
					log && console.log('wxLogin->++++++++++++++++++++++++++++++++++++++++++++登录失效重新登录', response);
					call && call(response);
				});
			}
		})
	}
}
/**
 * 微信小程序登录
 */
tui.wxAppletsLogin = function(call) {
	uni.login({
		success(res) {
			tui.post('/user/login', {
				code: res.code,
			}, {
				type: 'wx_applets'
			}, false).then(function(res) {
				switch (res.status) {
					case 0:
						tui.setUserInfo(res.data, function(response) {
							call && call(response);
						});
						break;
					default:
						console.log('wxAppletsLogin=>', res);
						break;
				}
			});
		}
	})
};
/**
 * 获取用户手机号
 */
tui.wxGetUserPhone = function(e, success, error) {
	if (e.errMsg === "getPhoneNumber:ok") {
		tui.post('/user/we/chat/applets/decrypt', {
			status: 1,
			iv: e.iv,
			encryptedData: e.encryptedData
		}).then(function(res) {
			switch (res.status) {
				case 0:
					tui.setUserInfo(res.data, function(response) {
						success && success(response);
					});
					break;
				default:
					console.log('wxGetUserPhone=>', res);
					break;
			}
		});
	}
	error && error(e);
};
// #endif
tui.getLocalFilePath = function(path) {
	if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
		return path
	}
	if (path.indexOf('file://') === 0) {
		return path
	}
	if (path.indexOf('/storage/emulated/0/') === 0) {
		return path
	}
	if (path.indexOf('/') === 0) {
		let localFilePath = plus.io.convertAbsoluteFileSystem(path)
		if (localFilePath !== path) {
			return localFilePath
		} else {
			path = path.substr(1)
		}
	}
	return '_www/' + path
};
tui.pathToBase64 = function(path) {
	return new Promise(function(resolve, reject) {
		if (typeof window === 'object' && 'document' in window) {
			if (typeof FileReader === 'function') {
				let xhr = new XMLHttpRequest();
				xhr.open('GET', path, true);
				xhr.responseType = 'blob';
				xhr.onload = function() {
					if (this.status === 200) {
						let fileReader = new FileReader();
						fileReader.onload = function(e) {
							resolve(e.target.result);
						};
						fileReader.onerror = reject;
						fileReader.readAsDataURL(this.response)
					}
				};
				xhr.onerror = reject;
				xhr.send();
				return
			}
			let canvas = document.createElement('canvas');
			let c2x = canvas.getContext('2d');
			let img = new Image;
			img.onload = function() {
				canvas.width = img.width;
				canvas.height = img.height;
				c2x.drawImage(img, 0, 0);
				resolve(canvas.toDataURL());
				canvas.height = canvas.width = 0
			};
			img.onerror = reject;
			img.src = path;
			return
		}
		if (typeof plus === 'object') {
			plus.io.resolveLocalFileSystemURL(tui.getLocalFilePath(path), function(entry) {
				entry.file(function(file) {
					let fileReader = new plus.io.FileReader();
					fileReader.onload = function(data) {
						resolve(data.target.result);
					};
					fileReader.onerror = function(error) {
						reject(error);
					};
					fileReader.readAsDataURL(file);
				}, function(error) {
					reject(error);
				})
			}, function(error) {
				reject(error);
			});
			return
		}
		if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
			wx.getFileSystemManager().readFile({
				filePath: path,
				encoding: 'base64',
				success(res) {
					resolve('data:image/png;base64,' + res.data)
				},
				fail(error) {
					reject(error)
				}
			});
			return
		}
		reject(new Error('not support'));
	})
};
tui.base64ToPath = function(base64) {
	return new Promise(function(resolve, reject) {
		if (typeof window === 'object' && 'document' in window) {
			base64 = base64.split(',')
			let type = base64[0].match(/:(.*?);/)[1];
			let str = atob(base64[1]);
			let n = str.length;
			let array = new Uint8Array(n);
			while (n--) {
				array[n] = str.charCodeAt(n);
			}
			return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
				type: type
			})));
		}
		let extName = base64.match(/data\:\S+\/(\S+);/);
		if (extName) {
			extName = extName[1];
		} else {
			reject(new Error('base64 error'));
		}
		let fileName = Date.now() + '.' + extName;
		if (typeof plus === 'object') {
			let bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now());
			bitmap.loadBase64Data(base64, function() {
				let filePath = '_doc/uniapp_temp/' + fileName;
				bitmap.save(filePath, {}, function() {
					bitmap.clear();
					resolve(filePath);
				}, function(error) {
					bitmap.clear();
					reject(error);
				})
			}, function(error) {
				bitmap.clear();
				reject(error);
			});
			return
		}
		if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
			let filePath = wx.env.USER_DATA_PATH + '/' + fileName;
			wx.getFileSystemManager().writeFile({
				filePath: filePath,
				data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
				encoding: 'base64',
				success() {
					resolve(filePath);
				},
				fail(error) {
					reject(error);
				}
			});
			return
		}
		reject(new Error('not support'));
	})
};
// 图片转换
tui.chooseImageToBase64 = function(count, callback) {
	uni.chooseImage({
		count: count,
		sizeType: ["original", "compressed"],
		sourceType: ["album"],
		success(res) {
			for (let i = 0; i < res.tempFilePaths.length; i++) {
				tui.pathToBase64(res.tempFilePaths[i]).then((paths) => {
					callback && callback(res.tempFilePaths, paths);
				}).catch((error) => {
					callback && callback(error);
				});
			}
		},
	});
};
tui.downloadFile = function(src) {
	uni.downloadFile({
		url: src,
		success: res => {
			console.log(res);
			if (res.statusCode === 200) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function() {
						tui.successMsg('保存成功');
					},
					fail: function() {
						tui.errorMsg('保存失败');
					}
				})
			} else {
				tui.errorMsg('保存失败');
			}
		}
	})
};
// 索引转选项
tui.asciiToIndex = function(n) {
	let ns = n + 1;
	let s = '';
	while (ns > 0) {
		let m = ns % 26;
		if (m === 0) m = 26;
		s = String.fromCharCode(m + 64) + s;
		ns = (ns - m) / 26;
	}
	return s;
};
/**
 * -----------------------------------------------
 * ------------------  未知  ---------------------
 * -----------------------------------------------
 */
tui.constNum = function() {
	let time = 0;
	// #ifdef APP-PLUS
	time = this.isAndroid() ? 300 : 0;
	// #endif
	return time
};
export default tui